#!usr/bin/env python
# -*- coding:utf-8 -*-
# user nanme: Mr.zhang
# data time : 2022/11/15   5:51 下午
# project   : init_datas.py
# IDE       : PyCharm
# email     :17600960626@163.com


import logging
import os
import re
import subprocess

from driver.conf_devices import devices
from init_data.get_devices import init_dev
from lib.read_file import Corpus
from lib.read_sql import db

class data_init(Corpus,devices):

    def boot_init(self,corpus_mode,mix_path,single_path,fuzzed_path):
        """分支入口"""
        self.initialize()
        L = 'DataLearn'
        F = 'fuzzed'
        if corpus_mode =="2":
            data = [i for i in self.read_corpus(self.base_path(mix_path)) if L in i]
            if L in data[0]:
                self.mixed_corpus(mix_path) # 混输效率测试

        elif corpus_mode =="1":
            data = [i for i in self.read_corpus(self.base_path(single_path)) if L in i]
            if L in data[0]:
                self.single_corpus(single_path)  # 单效率测试

        elif corpus_mode =="0":
            data = [i for i in self.read_fuzed(self.base_path(fuzzed_path)) if F in i]

            if F in data[0]:
                self.error_correction(fuzzed_path) # 纠错测试
        else:
            logging.error("输入错误")


    def initialize(self):
        """初始化设备"""
        sql = 'SELECT devices FROM zhu_lang WHERE `code`=2'
        sql1 = db.selectDb(sql)
        if len(sql1[1]) == 0:
            del_sql = 'truncate table zhu_lang'
            db.deleteDB(del_sql)
            logging.warning('初始化语料数据表完成')
        else:
            sql = 'select devices from dev_table where code = 0'
            sql1 = 'select id from zhu_lang where devices is NULL'
            a = db.selectDb(sql)
            b = db.selectDb(sql1)
            if a[1] == ():
                logging.error('没有空闲设备')
            elif b[1] == ():
                logging.error('语料表没有待测试数据')
            else:
                for j, i in zip(b[1], a[1]):
                    sql2 = 'update zhu_lang set devices="%s",code=0 where id ="%s"' % (i[0], j[0])
                    db.updateDb(sql2)

    def mixed_corpus(self,mix_path):
        '''混输获取输入效率主、副语言、语料路径入库'''
        path =self.base_path(mix_path)
        cors=os.listdir(path)
        for cors_name in cors:
            m = os.path.join(path,cors_name)
            if (os.path.isdir(m)):
                zhu_name = os.path.split(m)
                fu_path =path+"/"+zhu_name[1]
                file_name = os.listdir(fu_path)
                for x in file_name:
                    n = os.path.join(fu_path, x)
                    if (os.path.isdir(n)):
                        fu_name = os.path.split(n)
                        lens = len(zhu_name[1] + "_")
                        sql1 = 'INSERT INTO zhu_lang (zhu_table,fu_table,path_table)values ("%s","%s","%s")' \
                               % (zhu_name[1], fu_name[1][lens:],
                                  path+"/" + zhu_name[1] + "/" + fu_name[1] + "/" + fu_name[1] + 'DataLearn')
                        db.insertDB(sql1)

    def single_corpus(self,single_path):
        """单输入语料、语料路径入库"""
        path =self.base_path(single_path)
        cors=os.listdir(path)
        for cors_name in cors:
            if cors_name not in ".DS_Store":
                m = os.path.join(path,cors_name)
                if (os.path.isfile(m)):
                    zhu_name = os.path.split(m)
                    sql1 = 'INSERT INTO zhu_lang (zhu_table,path_table)values ("%s","%s")' \
                           % (zhu_name[1][:-9],path+"/" + zhu_name[1])
                    db.insertDB(sql1)


    def error_correction(self,fuzzed_path):
        """纠错测试"""
        path = self.base_path(fuzzed_path)
        cors = os.listdir(path)
        for cors_name in cors:
            if cors_name not in ".DS_Store":
                m = os.path.join(path, cors_name)
                if (os.path.isfile(m)):
                    zhu_name = os.path.split(m)
                    sql1 = 'INSERT INTO zhu_lang (zhu_table,path_table)values ("%s","%s")' \
                           % (zhu_name[1][:-19], path + "/" + zhu_name[1])
                    db.insertDB(sql1)

    def lang_devices(self):
        '''设备与对应语料绑定'''
        sql = 'select devices from dev_table where code = 0'
        sql1 = 'select id from zhu_lang where devices is NULL'
        a = db.selectDb(sql)
        b = db.selectDb(sql1)
        if a[1] == ():
            logging.error('没有空闲设备')
        elif b[1] == ():
            logging.error('语料表没有待测试数据')
        else:
            for j, i in zip(b[1], self.devlists()):
                sql2 = 'update zhu_lang set devices="%s",code=0 where id ="%s"' % (i, j[0])
                db.updateDb(sql2)
            logging.warning('入库完成…')


    def init_layout(self,layout):
        """推送layout文件"""
        layout_dic = self.read_layout(self.base_path(layout))
        sql = "SELECT zhu_table,devices FROM zhu_lang "
        a=db.selectDb(sql)
        for i in a[1]:
            layout_path=layout_dic["layout_"+i[0]]
            adb = "adb -s %s push %s /sdcard/layout_info"%(i[1],layout_path)
            subprocess.run(adb, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True,
                           universal_newlines=True)
            logging.warning("layout推送:%s,设备号：%s"%(i[0],i[1]))


                # adb = "adb -s %s push %s /sdcard/layout_info"%(a[1][0][1],self.base_path(layout)+"/"+j)
                # print(adb)
                # subprocess.run(adb, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True,
                #                universal_newlines=True)
                # logging.warning("语料推送成功:%s"%j)

# if __name__ == '__main__':
#     a=data_init()
#     a.init_layout(layout="/data/layout")